library(data.table)
library(plyr)
library(ggplot2)
library(reshape)
library(xtable)


## ggplot theme
arg.theme <- theme(panel.background=element_blank(),
                   panel.border=element_rect(colour = "black", fill=NA),
                   axis.text=element_text(color="black"),
                   strip.text.x=element_text(face='bold'),
                   axis.ticks = element_line(),
                   axis.text.x=element_text(size=12),
                   axis.text.y=element_text(size=12),
                   legend.text=element_text(size=12),
                   axis.title=element_text(size=12),
                   legend.title=element_text(size=12))


group.status.byyear <- data.table(read.csv(file="groups-by-country-year.csv", stringsAsFactors = FALSE))
group.status.byyear[, deliberate := ifelse(deliberate>=1, 1, 0)]
group.status.byyear[, contextual := ifelse(contextual>=1, 1, 0)]

by.year <- group.status.byyear[, list(count=sum(.N)), by=list(year,group_type)]
by.year[, group_type := as.numeric(group_type)]
by.year <- by.year[order(year, group_type), ]

## Figure 2 
over.time <- ggplot(by.year, aes(x=year, y=count, linetype=as.factor(group_type))) +
    geom_line(size=.9) +
    scale_linetype_manual("",labels=c("Anti-government", "Pro-government", "Unaligned"), values=c("solid", "dotdash", "dotted"))+
    scale_x_continuous("", breaks=by.year$year)+
    scale_y_continuous("Groups", breaks=c(25,50,75,100,125,150))+
    arg.theme +
    theme(axis.text.x = element_text(size=10,angle=90, vjust=.5,hjust=.5),
          panel.grid.minor = element_blank(),
          legend.position = "bottom")
ggsave(plot=over.time, file="Figure2-groups-over-time.pdf",  width=7, height=5)


## Table 3: number and type of alignement changes 
# deliberate [categorial]: Deliberate alignment change. 0 - No deliberate alignment change
# 1 - Co-optation by the government
# 2 - Defecting from peace agreement
# 3 - Other types of deliberate alignment
# contextual [categorial]: Contextual alignment change. 0 - No contextual alignment change 
# 1 - Loss of support by government
# 3 - Affiliated government loses power
# 5 - Reaching power
# 6 - Affiliated government returns to power 
# 8 - Kicked out of power
# 9 - Unclear

deliberate.changes <- unlist(strsplit(group.status.byyear$deliberate_type, ","))
deliberate.changes <- as.data.frame(table(deliberate.changes[-grep("0", deliberate.changes)]))
deliberate.changes$`Type of alignment change` <- c("Co-optation by the government", "Defecting from peace agreement","Non-formalized deliberate alignment")

contextual.changes  <- unlist(strsplit(group.status.byyear$contextual_type , ","))
contextual.changes <- as.data.frame(table(contextual.changes[-grep("0", contextual.changes)]))
contextual.changes$`Type of alignment change` <- c("Loss of support by government", "Affiliated government loses power", "Reaching power", "Affiliated government assumes power", "Removed from power", "Unclear")

changes <- rbind(deliberate.changes[,c(3,2)], contextual.changes[,c(3,2)])
names(changes)[2] <- "Frequency"
total <- sum(changes$Frequency)
changes <- rbind(changes, c("Total", total))
changes$Percentage <- paste(round(100* (as.numeric(changes$Frequency)/ total), 
                                  digits=1), "%", sep="")
# reorder 
changes <- changes[c(1,2,3,5,7,4,6,8,9,10), ]
print(xtable(changes,caption="Types of alignment changes", label="changes", digits=0),
      include.rownames=F,
      hline.after = c(-1,0,3,9,10),
      file="Table3-alignchanges.tex")


## Figure 3: Sierra Leone
SL <- group.status.byyear[gwno==451, list(year, group_type, deliberate, contextual, ucdp_name)]
SL <- SL[order(year, group_type), ]
SL[, Sideswitch := ifelse(deliberate==1, "Deliberate", "None")]
SL[, Sideswitch := ifelse(contextual==1, "Contextual",Sideswitch)]
SL[, Sideswitch := ifelse(contextual==1 & deliberate==1, "both", Sideswitch)]
SL[, Sideswitch := factor(Sideswitch, levels=c("None", "Deliberate", "Contextual", "Both"))]
SL[, group_type := as.factor(group_type)]

SL.plot <- ggplot() +
    geom_line(data=SL, aes(y=as.factor(ucdp_name), x=year), color="black", linetype="dotted")+
    geom_point(data=SL, aes(y=as.factor(ucdp_name), x=year, shape=Sideswitch, color=group_type), size=5) +    
    scale_colour_grey("Alignment:", labels=c("Anti-government", "Pro-government"),start = 0, end = .6) +
    scale_shape_manual("Alignment change:", values=c(16,15,17))+
  guides(shape = guide_legend(override.aes = list(shape = c(1,0,2)))) +
    scale_x_continuous("", breaks=unique(SL$year))+
    ylab("") +
    arg.theme +
    theme(axis.text.x = element_text(angle=90,vjust=0.5,hjust=.5),
          panel.grid.minor = element_blank(),
          legend.key = element_blank(),
          legend.position = "bottom",
          legend.box = "vertical")+
    guides(colour = guide_legend(override.aes = list(shape=95,size=15)))
ggsave(plot=SL.plot, file="Figure4-SL-groups.pdf", width=8, height=5.5)







